package com.example.houseman.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.example.houseman.entity.*;
import com.example.houseman.enums.*;
import com.example.houseman.mapper.*;
import com.example.houseman.service.ITSfContractService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.houseman.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.org.dto.CwPaymentPlanDto;
import com.org.dto.RequestDetailSfContractSaveDto;
import com.org.dto.TsfContractDto;
import com.org.vo.ResultEntity;
import com.org.vo.SysUserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 龚梦
 * @since 2021-04-02
 */
@Service
public class TSfContractServiceImpl extends ServiceImpl<TSfContractMapper, TSfContract> implements ITSfContractService {

    @Autowired
    TSfContractMapper contractMapper;

    @Autowired
    private TMOwnerMapper tmOwnerMapper;

    @Autowired
    private TCwPaymentPlanMapper tCwPaymentPlanMapper;

    @Autowired
    private TCwReceiptPlanMapper tCwReceiptPlanMapper;

    @Autowired
    private TbHouseInfoMapper tbHouseInfoMapper;

    @Autowired
    private TMAttachmentMapper tmAttachmentMapper;

    @Autowired
    private UserService userService;

    @Override
    public PageInfo<TSfContract> getlist(TsfContractDto tsfContractDto) {
        System.out.println(tsfContractDto + "=-=-=-=-=-=-");
        PageHelper.startPage(tsfContractDto.getPageNum(), tsfContractDto.getPageSize());
        List<TSfContract> list = contractMapper.getlist(tsfContractDto);
        return new PageInfo<>(list);
    }

    @Override
    public PageInfo<TSfContract> getlists(TsfContractDto tsfContractDto) {
        PageHelper.startPage(tsfContractDto.getPageNum(), tsfContractDto.getPageSize());
        List<TSfContract> list = contractMapper.getlists(tsfContractDto);
        return new PageInfo<>(list);
    }

    @Override
    public PageInfo<TSfContract> jie(TsfContractDto tsfContractDto) {
        PageHelper.startPage(tsfContractDto.getPageNum(), tsfContractDto.getPageSize());
        List<TSfContract> list = contractMapper.jie(tsfContractDto);

        for (TSfContract a : list
        ) {
            System.out.print(a);
        }
        return new PageInfo<>(list);
    }

    @Override
    public TSfContract getOnee(Integer id) {
        return contractMapper.getOnee(id);
    }


    //满
    @Override
    public PageInfo<TSfContract> selectList(TsfContractDto contractDto) {
        PageHelper.startPage(contractDto.getPageNum(), contractDto.getPageSize());
        List<TSfContract> selectList = contractMapper.selectContractList(contractDto);
        return new PageInfo<>(selectList);
    }

    @Override
    public ResultEntity updateStatus(TsfContractDto contractDto) {
        TSfContract contract = new TSfContract();
        BeanUtils.copyProperties(contractDto, contract);
        contract.setStatus(3);//已解约
        contract.setXyStatus(false);//未续约
        contractMapper.updateById(contract);
        return ResultEntity.ok("修改成功");
    }

    @Override
    public void saveSfContract(RequestDetailSfContractSaveDto requestDetailSfContractSaveDto) {
        //通过用户名查询用户
        SysUserVo sysUserVo = userService.findByUserName(requestDetailSfContractSaveDto.getUsername());
        Date nowTime = new Date();
        Long loginUserId = sysUserVo.getUserId();
        TMOwner mOwnerEntity = new TMOwner();
        BeanUtils.copyProperties(requestDetailSfContractSaveDto, mOwnerEntity);
        mOwnerEntity.setContractId(requestDetailSfContractSaveDto.getSfContractId());
        mOwnerEntity.setOwnerName(requestDetailSfContractSaveDto.getOwnerName());
        mOwnerEntity.setIdCard(requestDetailSfContractSaveDto.getOwnerIdCard());
        mOwnerEntity.setMobile(requestDetailSfContractSaveDto.getOwnerMobile());
        mOwnerEntity.setAddress(requestDetailSfContractSaveDto.getOwnerContactAddress());
        mOwnerEntity.setUrgMobile(requestDetailSfContractSaveDto.getSignUserEmergencyPhone());
        //mOwnerEntity.setBankCard(requestDetailSfContractSaveDto.getBankCard());
        //mOwnerEntity.setBankUserName(requestDetailSfContractSaveDto.getBankUserName());
        mOwnerEntity.setBankOpen(requestDetailSfContractSaveDto.getBankOpen());
        mOwnerEntity.setBankName(requestDetailSfContractSaveDto.getBankName());
        //mOwnerEntity.setBankUserIdCard(requestDetailSfContractSaveDto.getBankUserIdCard());
        mOwnerEntity.setAccountType(requestDetailSfContractSaveDto.getAccountType());//银行账户类型（对公账户、对私账户）
        mOwnerEntity.setBankCardNumber(requestDetailSfContractSaveDto.getBankCardNumber());//银行卡号
        mOwnerEntity.setAccountName(requestDetailSfContractSaveDto.getAccountName());//账户名称（对公为企业名称，对私为姓名）
        mOwnerEntity.setBankBranchCodeLh(requestDetailSfContractSaveDto.getBankBranchCodeLh());//联行行号（手输，对公必须）
        mOwnerEntity.setBankAccountProvince(requestDetailSfContractSaveDto.getBankAccountProvince());//开户行所在省ID
        // 共通设定
        mOwnerEntity.setCreateUserid(loginUserId);
        mOwnerEntity.setCreateTime(nowTime);
        mOwnerEntity.setUpdateUserid(loginUserId);
        mOwnerEntity.setUpdateTime(nowTime);
        tmOwnerMapper.insert(mOwnerEntity);

        // 根据房产id获取房产信息
        TbHouseInfo houseInfo = tbHouseInfoMapper.getHouseInfoByHouseId(requestDetailSfContractSaveDto.getHouseId());
        TSfContract tSfContract = new TSfContract();
        if (requestDetailSfContractSaveDto.getSignWithOwner() == null) {
            requestDetailSfContractSaveDto.setSignWithOwner(false);
        }
        // 签约人是否为业主
        if (requestDetailSfContractSaveDto.getSignWithOwner().equals(true)) {
            tSfContract.setSignUserName(requestDetailSfContractSaveDto.getOwnerName());
            tSfContract.setSignUserIdCard(requestDetailSfContractSaveDto.getOwnerIdCard());
            tSfContract.setSignUserMobile(requestDetailSfContractSaveDto.getOwnerMobile());
        } else if (requestDetailSfContractSaveDto.getSignWithOwner().equals(false)) {
            tSfContract.setSignUserName(requestDetailSfContractSaveDto.getSignUserName());
            tSfContract.setSignUserIdCard(requestDetailSfContractSaveDto.getSignUserIdCard());
            tSfContract.setSignUserMobile(requestDetailSfContractSaveDto.getSignUserMobile());
        }
        BeanUtils.copyProperties(requestDetailSfContractSaveDto, tSfContract);

        String contractNo = "";
        try {
            //contractNo = itmSequenceService.getSerialNumber(SerialType.SHOUFANGHETONG);
            contractNo = UUID.randomUUID().toString();
        } catch (Exception e) {
            throw e;
        }
        tSfContract.setHouseId(requestDetailSfContractSaveDto.getHouseId());
        tSfContract.setSfContractNo(contractNo);
        // 业主ID
        tSfContract.setOwnerId(mOwnerEntity.getId());
        // 合同开始时间
        tSfContract.setLeaseStartTime(requestDetailSfContractSaveDto.getLesaseStartTime());
        // 合同结束时间
        tSfContract.setLeaseEndTime(requestDetailSfContractSaveDto.getLeaseEndTime());
        // 签约时间
        tSfContract.setConSignTime(nowTime);
        // 录入日期
        tSfContract.setConInfoTime(nowTime);
        // 审核日期
        tSfContract.setConAudTime(nowTime);
        // 押金
        tSfContract.setDepositMoney(requestDetailSfContractSaveDto.getDepositMoney());
        // 合同录入人
        tSfContract.setOperId(loginUserId);
        // 收房人ID
        tSfContract.setSfUserId(loginUserId);
        // 是否未签约人
        tSfContract.setSignWithOwner(requestDetailSfContractSaveDto.getSignWithOwner());
        // 收房人姓名
        tSfContract.setSfUserName(requestDetailSfContractSaveDto.getUsername());
        // 合同状态（1，草稿。2，已提交。3，已解约。4，已结束。9:作废）
        tSfContract.setStatus(ContractStateEnum.SUBMITED.getIndex());

        int houseLeaseType = 3;
        if (null != houseInfo.getReserve1()) {
            if (houseInfo.getReserve1() == 1) {
                houseLeaseType = 1;
            } else if (houseInfo.getReserve1() == 2) {
                houseLeaseType = 2;
            }
        }
        tSfContract.setHouseLeaseType(houseLeaseType);
        // 续约状态（0，未续约。1，已续约）
        tSfContract.setXyStatus(true);
        tSfContract.setBankCard(requestDetailSfContractSaveDto.getBankCardNumber());//银行卡号
        // 共通设定项
        tSfContract.setDelFlg(false);
        tSfContract.setUpdateUserid(loginUserId);
        tSfContract.setUpdateTime(nowTime);
        tSfContract.setCreateUserid(loginUserId);
        tSfContract.setCreateTime(nowTime);
        tSfContract.setBusinessId(sysUserVo.getBusinessId().longValue());
        tSfContract.setDeptId(sysUserVo.getDeptId());
        baseMapper.insert(tSfContract);
        // 续约时
        if (tSfContract.getLastContractId() != null) {
            // 获取原合同
            TSfContract sfEntity = baseMapper.selectById(tSfContract.getLastContractId());
            // 更新原合同的续约状态
            sfEntity.setXyStatus(true);
            sfEntity.setUpdateTime(new Date());
            sfEntity.setUpdateUserid(loginUserId);
            sfEntity.setDepositMoney(new BigDecimal("0"));
            baseMapper.updateById(sfEntity);
            // 生成收款计划 - 支付原合同 - 押金
            TCwReceiptPlan rec = new TCwReceiptPlan();
            String recNo = "";
            try {
                //recNo = itmSequenceService.getSerialNumber(SerialType.SHOUKUANJIHUA);
                recNo = UUID.randomUUID().toString();
            } catch (Exception e) {
                throw e;
            }
            // 收款计划编号
            rec.setReceiptOrderNo(recNo);
            // 商户ID
            rec.setBusinessId(sfEntity.getBusinessId().longValue());
            // 收房合同ID
            rec.setContractId(sfEntity.getId());
            // 收房合同单号
            rec.setContractNo(sfEntity.getSfContractNo());
            // 合同类型：收房合同
            rec.setContractType(ContractTypeEnum.SF.getIndex());
            // 楼盘ID
            rec.setPremiseId(houseInfo.getPremisesId().longValue());
            // 小区
            rec.setPremiseName(requestDetailSfContractSaveDto.getPremiseName());
            // 业主ID
            rec.setOwnerId(sfEntity.getOwnerId());
            // 业主名称
            rec.setOwnerName(sfEntity.getOwnerName());
            // 收款类型
            rec.setReceiptType(ReceiptTypeEnum.FZ.getIndex());
            // 收款状态
            rec.setSkStatus(SkStatusEnum.YSK.getIndex());
            // 账单类型
            rec.setBillType(CollectionPlanZdType.PTZD.getIndex());
            // 款项
            rec.setItemType(BusinessCostTypesEnum.YAJIN.getIndex());
            // 支付金额（应收金额）合计
            BigDecimal depositMoney = requestDetailSfContractSaveDto.getDepositMoney();
            rec.setPaymentAmount(new BigDecimal(Math.abs(depositMoney.doubleValue()) + ""));
            // 租金 //收房合同租金
            rec.setRentalPrice(tSfContract.getMonthRent());
            // 账期开始日
            rec.setPaymentDaysBegin(nowTime);
            // 操作人
            rec.setOperationUser(requestDetailSfContractSaveDto.getUsername());// 操作人
            // 备注
            rec.setRemark(requestDetailSfContractSaveDto.getRemark());
            // 共通
            rec.setDelFlg(false);
            rec.setCreateTime(nowTime);
            rec.setUpdateTime(nowTime);
            rec.setCreateUserid(loginUserId);
            rec.setUpdateUserid(loginUserId);
            tCwReceiptPlanMapper.insert(rec);
        }
        // 添加房产附件信息
        /**
         * 附件保存： ① 业务对象ID,附件所属对应的业务数据ID，比如：合同/协议ID ②
         * 附件所属区分,"10：收房合同，11：收房解约协议，20：出房合同，21：出房解约协议" ③
         * 附件类型,"1:房产证，2：收房合同，3：业主身份证，4：代理人身份证，5：银行卡信息，
         * 6：委托书，7：解约合同，8：租赁合同，9：客户身份证，10：物业交割单，99：其他"
         */
        // 业务对象ID
        Long relationId = tSfContract.getId();
        // 附件所属区分
        Integer relationType = AttachmentRelationTypeEnum.SFHT.getIndex();
        // 保存房产证件
        saveAttachement(relationId, relationType, AttachmentTypeEnum.FCZ.getIndex(),
                requestDetailSfContractSaveDto.getHouseDocumentPhotos(), loginUserId);
        // 保存收房合同
        saveAttachement(relationId, relationType, AttachmentTypeEnum.SFHT.getIndex(),
                requestDetailSfContractSaveDto.getContractPhotos(), loginUserId);
        // 保存业主身份证
        saveAttachement(relationId, relationType, AttachmentTypeEnum.YZSFZ.getIndex(), requestDetailSfContractSaveDto.getCardPhotos(), loginUserId);
        // 代理人身份证
        saveAttachement(relationId, relationType, AttachmentTypeEnum.DLRSFZ.getIndex(),
                requestDetailSfContractSaveDto.getAgentCardPhotos(), loginUserId);
        // 银行卡信息
        saveAttachement(relationId, relationType, AttachmentTypeEnum.YHKXX.getIndex(),
                requestDetailSfContractSaveDto.getBankCardInformationPhotos(), loginUserId);
        // 委托书
        saveAttachement(relationId, relationType, AttachmentTypeEnum.WTS.getIndex(),
                requestDetailSfContractSaveDto.getAttorneyPhotos(), loginUserId);
        // 保存物业交割单
        saveAttachement(relationId, relationType, AttachmentTypeEnum.WYJGD.getIndex(),
                requestDetailSfContractSaveDto.getPropertyDeliverys(), loginUserId);
        // 保存其他
        saveAttachement(relationId, relationType, AttachmentTypeEnum.QT.getIndex(),
                requestDetailSfContractSaveDto.getOtherPhotos(), loginUserId);

        List<CwPaymentPlanDto> payPlan = requestDetailSfContractSaveDto.getPayMentltems();
        if (payPlan != null) {
            for (CwPaymentPlanDto cwPaymentPlanDto : payPlan) {
                TCwPaymentPlan tCwPaymentPlan = new TCwPaymentPlan();
                BeanUtils.copyProperties(cwPaymentPlanDto, tCwPaymentPlan);
                // 付款计划编号
                String payOrderNo = "";
                try {
                    //payOrderNo = itmSequenceService.getSerialNumber(SerialType.FUKUANJIHUA);
                    payOrderNo = UUID.randomUUID().toString();
                } catch (Exception e) {
                    throw e;
                }
                tCwPaymentPlan.setPayNumber(cwPaymentPlanDto.getPayNumber());
                tCwPaymentPlan.setPayOrderNo(payOrderNo);
                tCwPaymentPlan.setPayableDate(cwPaymentPlanDto.getPayableDate());
                // 商户ID
                tCwPaymentPlan.setBusinessId(sysUserVo.getBusinessId().longValue());
                // 收房合同ID
                tCwPaymentPlan.setContractId(tSfContract.getId());
                // 收房合同编号
                tCwPaymentPlan.setContractNo(tSfContract.getSfContractNo());
                // 合同类型（收房合同）
                tCwPaymentPlan.setContractType(ContractTypeEnum.SF.getIndex());
                // 楼盘id
                if (!houseInfo.equals(null)) {
                    tCwPaymentPlan.setPremiseId(new Long(houseInfo.getPremisesId()));
                }
                // 楼盘名称(同小区名称)
                tCwPaymentPlan.setPremiseName(requestDetailSfContractSaveDto.getPremiseName());
                // 业主ID
                tCwPaymentPlan.setOwnerId(requestDetailSfContractSaveDto.getOwnerId());
                // 业主姓名
                tCwPaymentPlan.setOwnerName(requestDetailSfContractSaveDto.getOwnerName());
                // 账单类型
                tCwPaymentPlan.setBillType(PayPlanZdType.PTZD.getIndex());
                // 付款类型
                tCwPaymentPlan.setPayType(PaymentTypeEnum.SFFK.getIndex());
                // 付款状态
                tCwPaymentPlan.setPayState(0);
                // 操作人
                tCwPaymentPlan.setOperationUser(requestDetailSfContractSaveDto.getUsername());
                // 共通设定
                tCwPaymentPlan.setCreateUserid(loginUserId);
                tCwPaymentPlan.setCreateTime(nowTime);
                tCwPaymentPlan.setUpdateUserid(loginUserId);
                tCwPaymentPlan.setUpdateTime(nowTime);
                tCwPaymentPlan.setItemType(cwPaymentPlanDto.getItemType());
                tCwPaymentPlanMapper.insert(tCwPaymentPlan);
            }
        }
    }

    @Override
    public void extensionSfContract(RequestDetailSfContractSaveDto requestDetailSfContractSaveDto) {
        SysUserVo sysUserVo = userService.findByUserName(requestDetailSfContractSaveDto.getUsername());
        Date nowTime = new Date();
        Long loginUserId = sysUserVo.getUserId();
        TMOwner mOwnerEntity = new TMOwner();
        BeanUtils.copyProperties(requestDetailSfContractSaveDto, mOwnerEntity);
        mOwnerEntity.setContractId(requestDetailSfContractSaveDto.getSfContractId());
        mOwnerEntity.setOwnerName(requestDetailSfContractSaveDto.getOwnerName());
        mOwnerEntity.setIdCard(requestDetailSfContractSaveDto.getOwnerIdCard());
        mOwnerEntity.setMobile(requestDetailSfContractSaveDto.getOwnerMobile());
        mOwnerEntity.setAddress(requestDetailSfContractSaveDto.getOwnerContactAddress());
        mOwnerEntity.setUrgMobile(requestDetailSfContractSaveDto.getSignUserEmergencyPhone());
        //mOwnerEntity.setBankCard(requestDetailSfContractSaveDto.getBankCard());
        //mOwnerEntity.setBankUserName(requestDetailSfContractSaveDto.getBankUserName());
        mOwnerEntity.setBankOpen(requestDetailSfContractSaveDto.getBankOpen());
        mOwnerEntity.setBankName(requestDetailSfContractSaveDto.getBankName());
        //mOwnerEntity.setBankUserIdCard(requestDetailSfContractSaveDto.getBankUserIdCard());
        mOwnerEntity.setAccountType(requestDetailSfContractSaveDto.getAccountType());//银行账户类型（对公账户、对私账户）
        mOwnerEntity.setBankCardNumber(requestDetailSfContractSaveDto.getBankCardNumber());//银行卡号
        mOwnerEntity.setAccountName(requestDetailSfContractSaveDto.getAccountName());//账户名称（对公为企业名称，对私为姓名）
        mOwnerEntity.setBankBranchCodeLh(requestDetailSfContractSaveDto.getBankBranchCodeLh());//联行行号（手输，对公必须）
        mOwnerEntity.setBankAccountProvince(requestDetailSfContractSaveDto.getBankAccountProvince());//开户行所在省ID
        // 共通设定
        mOwnerEntity.setCreateUserid(loginUserId);
        mOwnerEntity.setCreateTime(nowTime);
        mOwnerEntity.setUpdateUserid(loginUserId);
        mOwnerEntity.setUpdateTime(nowTime);
        tmOwnerMapper.insert(mOwnerEntity);

        // 根据房产id获取房产信息
        TbHouseInfo houseInfo = tbHouseInfoMapper.getHouseInfoByHouseId(requestDetailSfContractSaveDto.getHouseId());
        TSfContract tSfContract = new TSfContract();
        if (requestDetailSfContractSaveDto.getSignWithOwner() == null) {
            requestDetailSfContractSaveDto.setSignWithOwner(false);
        }
        // 签约人是否为业主
        if (requestDetailSfContractSaveDto.getSignWithOwner().equals(true)) {
            tSfContract.setSignUserName(requestDetailSfContractSaveDto.getOwnerName());
            tSfContract.setSignUserIdCard(requestDetailSfContractSaveDto.getOwnerIdCard());
            tSfContract.setSignUserMobile(requestDetailSfContractSaveDto.getOwnerMobile());
        } else if (requestDetailSfContractSaveDto.getSignWithOwner().equals(false)) {
            tSfContract.setSignUserName(requestDetailSfContractSaveDto.getSignUserName());
            tSfContract.setSignUserIdCard(requestDetailSfContractSaveDto.getSignUserIdCard());
            tSfContract.setSignUserMobile(requestDetailSfContractSaveDto.getSignUserMobile());
        }
        BeanUtils.copyProperties(requestDetailSfContractSaveDto, tSfContract);

        String contractNo = "";
        try {
            //contractNo = itmSequenceService.getSerialNumber(SerialType.SHOUFANGHETONG);
            contractNo = UUID.randomUUID().toString();
        } catch (Exception e) {
            throw e;
        }
        tSfContract.setHouseId(requestDetailSfContractSaveDto.getHouseId());
        tSfContract.setSfContractNo(contractNo);
        // 业主ID
        tSfContract.setOwnerId(mOwnerEntity.getId());
        // 合同开始时间
        tSfContract.setLeaseStartTime(requestDetailSfContractSaveDto.getLesaseStartTime());
        // 合同结束时间
        tSfContract.setLeaseEndTime(requestDetailSfContractSaveDto.getLeaseEndTime());
        // 签约时间
        tSfContract.setConSignTime(nowTime);
        // 录入日期
        tSfContract.setConInfoTime(nowTime);
        // 审核日期
        tSfContract.setConAudTime(nowTime);
        // 押金
        tSfContract.setDepositMoney(requestDetailSfContractSaveDto.getDepositMoney());
        // 合同录入人
        tSfContract.setOperId(loginUserId);
        // 收房人ID
        tSfContract.setSfUserId(loginUserId);
        // 是否未签约人
        tSfContract.setSignWithOwner(requestDetailSfContractSaveDto.getSignWithOwner());
        // 收房人姓名
        tSfContract.setSfUserName(requestDetailSfContractSaveDto.getUsername());
        // 合同状态（1，草稿。2，已提交。3，已解约。4，已结束。9:作废）
        tSfContract.setStatus(ContractStateEnum.SUBMITED.getIndex());

        int houseLeaseType = 3;
        if (null != houseInfo.getReserve1()) {
            if (houseInfo.getReserve1() == 1) {
                houseLeaseType = 1;
            } else if (houseInfo.getReserve1() == 2) {
                houseLeaseType = 2;
            }
        }
        tSfContract.setHouseLeaseType(houseLeaseType);
        // 续约状态（0，未续约。1，已续约）
        tSfContract.setXyStatus(true);
        tSfContract.setBankCard(requestDetailSfContractSaveDto.getBankCardNumber());//银行卡号
        // 共通设定项
        tSfContract.setDelFlg(false);
        tSfContract.setUpdateUserid(loginUserId);
        tSfContract.setUpdateTime(nowTime);
        tSfContract.setCreateUserid(loginUserId);
        tSfContract.setCreateTime(nowTime);
        tSfContract.setBusinessId(sysUserVo.getBusinessId().longValue());
        tSfContract.setDeptId(sysUserVo.getDeptId());
        tSfContract.setId(tSfContract.getLastContractId());
        baseMapper.updateById(tSfContract);
        // 续约时
        if (tSfContract.getLastContractId() != null) {
            // 获取原合同
            TSfContract sfEntity = baseMapper.selectById(tSfContract.getLastContractId());
            // 更新原合同的续约状态
            sfEntity.setXyStatus(true);
            sfEntity.setUpdateTime(new Date());
            sfEntity.setUpdateUserid(loginUserId);
            sfEntity.setDepositMoney(new BigDecimal("0"));
            baseMapper.updateById(sfEntity);
            // 生成收款计划 - 支付原合同 - 押金
            TCwReceiptPlan rec = new TCwReceiptPlan();
            String recNo = "";
            try {
                //recNo = itmSequenceService.getSerialNumber(SerialType.SHOUKUANJIHUA);
                recNo = UUID.randomUUID().toString();
            } catch (Exception e) {
                throw e;
            }
            // 收款计划编号
            rec.setReceiptOrderNo(recNo);
            // 商户ID
            rec.setBusinessId(sfEntity.getBusinessId().longValue());
            // 收房合同ID
            rec.setContractId(sfEntity.getId());
            // 收房合同单号
            rec.setContractNo(sfEntity.getSfContractNo());
            // 合同类型：收房合同
            rec.setContractType(ContractTypeEnum.SF.getIndex());
            // 楼盘ID
            rec.setPremiseId(houseInfo.getPremisesId().longValue());
            // 小区
            rec.setPremiseName(requestDetailSfContractSaveDto.getPremiseName());
            // 业主ID
            rec.setOwnerId(sfEntity.getOwnerId());
            // 业主名称
            rec.setOwnerName(sfEntity.getOwnerName());
            // 收款类型
            rec.setReceiptType(ReceiptTypeEnum.FZ.getIndex());
            // 收款状态
            rec.setSkStatus(SkStatusEnum.YSK.getIndex());
            // 账单类型
            rec.setBillType(CollectionPlanZdType.PTZD.getIndex());
            // 款项
            rec.setItemType(BusinessCostTypesEnum.YAJIN.getIndex());
            // 支付金额（应收金额）合计
            BigDecimal depositMoney = requestDetailSfContractSaveDto.getDepositMoney();
            rec.setPaymentAmount(new BigDecimal(Math.abs(depositMoney.doubleValue()) + ""));
            // 租金 //收房合同租金
            rec.setRentalPrice(tSfContract.getMonthRent());
            // 账期开始日
            rec.setPaymentDaysBegin(nowTime);
            // 操作人
            rec.setOperationUser(requestDetailSfContractSaveDto.getUsername());// 操作人
            // 备注
            rec.setRemark(requestDetailSfContractSaveDto.getRemark());
            // 共通
            rec.setDelFlg(false);
            rec.setCreateTime(nowTime);
            rec.setUpdateTime(nowTime);
            rec.setCreateUserid(loginUserId);
            rec.setUpdateUserid(loginUserId);
            tCwReceiptPlanMapper.insert(rec);
        }
        // 添加房产附件信息
        /**
         * 附件保存： ① 业务对象ID,附件所属对应的业务数据ID，比如：合同/协议ID ②
         * 附件所属区分,"10：收房合同，11：收房解约协议，20：出房合同，21：出房解约协议" ③
         * 附件类型,"1:房产证，2：收房合同，3：业主身份证，4：代理人身份证，5：银行卡信息，
         * 6：委托书，7：解约合同，8：租赁合同，9：客户身份证，10：物业交割单，99：其他"
         */
        // 业务对象ID
        Long relationId = tSfContract.getId();
        // 附件所属区分
        Integer relationType = AttachmentRelationTypeEnum.SFHT.getIndex();
        // 保存房产证件
        saveAttachement(relationId, relationType, AttachmentTypeEnum.FCZ.getIndex(),
                requestDetailSfContractSaveDto.getHouseDocumentPhotos(), loginUserId);
        // 保存收房合同
        saveAttachement(relationId, relationType, AttachmentTypeEnum.SFHT.getIndex(),
                requestDetailSfContractSaveDto.getContractPhotos(), loginUserId);
        // 保存业主身份证
        saveAttachement(relationId, relationType, AttachmentTypeEnum.YZSFZ.getIndex(), requestDetailSfContractSaveDto.getCardPhotos(), loginUserId);
        // 代理人身份证
        saveAttachement(relationId, relationType, AttachmentTypeEnum.DLRSFZ.getIndex(),
                requestDetailSfContractSaveDto.getAgentCardPhotos(), loginUserId);
        // 银行卡信息
        saveAttachement(relationId, relationType, AttachmentTypeEnum.YHKXX.getIndex(),
                requestDetailSfContractSaveDto.getBankCardInformationPhotos(), loginUserId);
        // 委托书
        saveAttachement(relationId, relationType, AttachmentTypeEnum.WTS.getIndex(),
                requestDetailSfContractSaveDto.getAttorneyPhotos(), loginUserId);
        // 保存物业交割单
        saveAttachement(relationId, relationType, AttachmentTypeEnum.WYJGD.getIndex(),
                requestDetailSfContractSaveDto.getPropertyDeliverys(), loginUserId);
        // 保存其他
        saveAttachement(relationId, relationType, AttachmentTypeEnum.QT.getIndex(),
                requestDetailSfContractSaveDto.getOtherPhotos(), loginUserId);

        List<CwPaymentPlanDto> payPlan = requestDetailSfContractSaveDto.getPayMentltems();
        if (payPlan != null) {
            for (CwPaymentPlanDto cwPaymentPlanDto : payPlan) {
                TCwPaymentPlan tCwPaymentPlan = new TCwPaymentPlan();
                BeanUtils.copyProperties(cwPaymentPlanDto, tCwPaymentPlan);
                // 付款计划编号
                String payOrderNo = "";
                try {
                    //payOrderNo = itmSequenceService.getSerialNumber(SerialType.FUKUANJIHUA);
                    payOrderNo = UUID.randomUUID().toString();
                } catch (Exception e) {
                    throw e;
                }
                tCwPaymentPlan.setPayNumber(cwPaymentPlanDto.getPayNumber());
                tCwPaymentPlan.setPayOrderNo(payOrderNo);
                // 商户ID
                tCwPaymentPlan.setBusinessId(sysUserVo.getBusinessId().longValue());
                // 收房合同ID
                tCwPaymentPlan.setContractId(tSfContract.getId());
                // 收房合同编号
                tCwPaymentPlan.setContractNo(tSfContract.getSfContractNo());
                // 合同类型（收房合同）
                tCwPaymentPlan.setContractType(ContractTypeEnum.SF.getIndex());
                // 楼盘id
                if (!houseInfo.equals(null)) {
                    tCwPaymentPlan.setPremiseId(new Long(houseInfo.getPremisesId()));
                }
                // 楼盘名称(同小区名称)
                tCwPaymentPlan.setPremiseName(requestDetailSfContractSaveDto.getPremiseName());
                // 业主ID
                tCwPaymentPlan.setOwnerId(requestDetailSfContractSaveDto.getOwnerId());
                // 业主姓名
                tCwPaymentPlan.setOwnerName(requestDetailSfContractSaveDto.getOwnerName());
                // 账单类型
                tCwPaymentPlan.setBillType(PayPlanZdType.PTZD.getIndex());
                // 付款类型
                tCwPaymentPlan.setPayType(PaymentTypeEnum.SFFK.getIndex());
                // 付款状态
                tCwPaymentPlan.setPayState(cwPaymentPlanDto.getSkStatus());
                // 操作人
                tCwPaymentPlan.setOperationUser(requestDetailSfContractSaveDto.getUsername());
                // 共通设定
                tCwPaymentPlan.setCreateUserid(loginUserId);
                tCwPaymentPlan.setCreateTime(nowTime);
                tCwPaymentPlan.setUpdateUserid(loginUserId);
                tCwPaymentPlan.setUpdateTime(nowTime);
                tCwPaymentPlan.setItemType(cwPaymentPlanDto.getItemType());
                tCwPaymentPlanMapper.updateById(tCwPaymentPlan);
            }
        }
    }

    /**
     * 保存附件信息
     *
     * @param relationId     业务对象ID
     * @param relationType   附件所属区分
     * @param attachmentType 附件类型
     * @param urls           附件项目url
     * @param userId         操作人id
     */
    private void saveAttachement(Long relationId, Integer relationType, Integer attachmentType, String[] urls,
                                 Long userId) {
        if (urls != null) {
            for (String url : urls) {
                if (StringUtils.isEmpty(url)) {
                    continue;
                }
                TMAttachment mAttachmentEntity = new TMAttachment();
                mAttachmentEntity.setRelationId(relationId);
                mAttachmentEntity.setRelationType(relationType);
                // 附件类型
                mAttachmentEntity.setAttachmentType(attachmentType);
                // 图片路径
                mAttachmentEntity.setUrl(url);
                // 共通设定项
                mAttachmentEntity.setUpdateUserid(userId);
                mAttachmentEntity.setUpdateTime(new Date());
                mAttachmentEntity.setCreateUserid(userId);
                mAttachmentEntity.setCreateTime(new Date());
                tmAttachmentMapper.insert(mAttachmentEntity);
            }
        }
    }
}
